/** ******************系统公共脚本************************ */
//系统自定异步请求提示
window.ajaxError = function (msg) {
    alert(msg);
}
//统一设置ajax请求编码方式,并禁用缓存
$.ajaxSetup({
    cache: false,
    contentType: "application/x-www-form-urlencoded; charset=utf-8"
});
$(function () {
    //点击搜索按钮
    $(document).on("click", '.searchCriteria .widget-buttons .businessBtns .search', function (event) {
        //var form = $(".searchCriteria .search_Bar form:first");
        var form=$(".searchConditions");
        if (form) {
            var viewPath = form.attr("action");
            var isRecord = false;
            var method = form.attr("method");
            var params = form.serializeArray();
            var showVal =$("#iconchangemore").attr("value");
            toView(viewPath, isRecord, method, params)
            setTimeout(function () {
                $("#iconchangemore").attr("value",showVal);
                if(showVal=="0"){
                    $("#iconchangemore .fa").removeClass("fa-chevron-down").addClass("fa-chevron-up");
                    $(".search_Bar_item").each(function () {
                        $(this).removeClass("hidden");
                    })
                }
            },200)
        }
    });
    var isInnerEdit = true;
    //点击新增、修改按钮
    $(document).on("click", ".searchCriteria .widget-buttons .businessBtns .add,.searchCriteria .widget-buttons .businessBtns .update,.dataTable .update,.fixedTable .update", function (event) {
        var that = $(this);
        var serializeNum = $(this).attr("serializeNum");
        var url = $(this).attr("editUrl");
        var params = {serializeNum: serializeNum};
        if ($(this).hasClass("update")) {
            var id = "";
            var checkedIds = getCheckedInputValues();
            if (checkedIds) {
                var idsArray = checkedIds.split(",");
                var length = idsArray.length;
                id = idsArray[length - 1];
                params = {
                    id: id,
                    serializeNum: serializeNum
                }
            } else {
                var targetDataId = $(this).attr("targetDataId");
                if (targetDataId) {
                    params = {
                        id: targetDataId,
                        serializeNum: serializeNum
                    }
                } else {
                    alert("请选择要编辑的记录!");
                    return false;
                }
            }
        }
        if (isInnerEdit == true) {
            var viewPath = url;
            var isRecord = true;
            var method = "GET";
            toView(viewPath, isRecord, method, params);
        } else {
            $("[id^=editDialog_]*").remove();
            var dialog = $('<div class="modal fade " id="editDialog_' + serializeNum + '" tabindex="-1" role="dialog" aria-labelledby="dialog" aria-hidden="true" style="display: none;">'
                + '<div class="modal-dialog">'
                + '<div class="modal-content">'
                //弹出层内容
                + '</div>'
                + '</div>'
                + '</div>');
            ajaxRequest(url, params, function (editFormHtml) {
                dialog.find(".modal-content").html(editFormHtml);
                $("#editDialog_" + serializeNum).remove();
                dialog.modal({
                    backdrop: "static",
                    show: true
                });
            }, function (XMLHttpRequest, textStatus, errorThrown) {
                ajaxError(errorThrown);
            }, "GET", "HTML");
        }
        //编辑表单回调
        $(document).on("ajaxSubmitCallback", "#editForm_" + serializeNum, function (event, data) {
            if (data.resCode == 200) {
                alert(data.resMsg);
                resetValidatorForm(this);
                if (isInnerEdit == true) {
                    //backView();
                } else {
                    dialog.modal("hide");
                    that.parents(".widget").find(".searchCriteria .widget-buttons .businessBtns .search").click();
                }
            } else {
                ajaxError(data.resMsg);
            }
        });
    });

    //点击删除按钮
    $(document).on("click", ".searchCriteria .widget-buttons .businessBtns .batchDelete,.fixedTable .delete", function (event) {
        if (!confirm("确认删除?")) {
            return false;
        }
        var that = $(this);
        var url;
        var params = {};
        if ($(this).hasClass("batchDelete")) {
            var checkedIds = getCheckedInputValues();
            if (checkedIds) {
                url = $(this).attr("batchDeleteUrl");
                params = {ids: checkedIds}
            } else {
                alert("请选择要删除的记录!");
                return;
            }
        } else {
            var targetDataId = $(this).attr("targetDataId");
            if (targetDataId) {
                url = $(this).attr("deleteUrl");
                params = {id: targetDataId}
            }
        }
        ajaxRequest(url, params, function (result) {
            if (result.resCode == "200") {
                console.log(that.parents(".widget").find(".searchBtn:first"));
                that.parents(".widget").find(".searchCriteria .widget-buttons .businessBtns .search").click();
                var targetCallbackClickTagId = that.attr("targetCallbackClickTagId");
                if (targetCallbackClickTagId) {
                    $("#" + targetCallbackClickTagId).click();
                }
            } else {
                alert(result.resMsg);
            }
        }, function (XMLHttpRequest, textStatus, errorThrown) {
            ajaxError(errorThrown);
        }, "GET", "JSON");
    });

    //更多筛选条件折叠效果
    $(document).on("click", "[data-toggle='moreConditions']", function () {
        var $moreConditions = $(this).parents(".widget").find(".moreConditions");
        if ($moreConditions.hasClass("hidden")) {
            $moreConditions.removeClass("hidden").addClass("slideInRight");
        } else {
            $moreConditions.removeClass("slideInRight").addClass("slideOutRight");
            if (window.toggleTimer) {
                clearTimeout(window.toggleTimer);
            }
            window.toggleTimer = setTimeout(function () {
                $moreConditions.removeClass("slideOutRight").addClass("hidden");
            }, 500);
        }
        $(this).find("i").toggleClass("fa-search-plus").toggleClass("fa-search-minus");
    });

    //点击导出按钮
    $(document).on("click", ".searchCriteria .widget-buttons .businessBtns .download", function (event) {

    });

    //条件输入区回车自动搜索
    $(document).on("keypress", '.searchCriteria .search_Bar input', function (e) {
        if (e.which == 13) {
            $(".searchCriteria .widget-buttons .businessBtns .search").click();
        }
    });

    //弹出层底部提交按钮提交弹出层内部表单
    $(document).on("click", ".modalSubmitBtn", function () {
        var dialog = $(this).parents(".modal-dialog");
        var modal_body = dialog.find(".modal-body");
        var forms = modal_body.find("form");
        forms.each(function (index, form) {
            $(form).submit();
        });
    });

    //列表页，回车翻页
    $(document).on("keypress", ".pagingBar input[name='targetPageNo'],.pagingBar input[name='targetPageSize']", function (e) {
        if (e.which == 13) {
            $(this).parents(".pagingBar").find(".searchBtn").click();

        }
    });

    //视图区重新自适应
    $(document).on("resize", ".widget", function () {
        $(this).find(".dataTables_scrollHeadInner").width("100%");
        $(this).find(".dataTables_scroll").css("width", "100%").find("table").css("width", "100%");
    });

    //数据列表全选反选
    $(document).on("change", ".chkAll:checkbox", function () {
        var _this = this;
        if ($(_this).parents(".fixedTableHead").size() > 0) {
            var table = $("[fixedTableHead='" + $(_this).parents(".fixedTableHead").attr("fxiedFor") + "'] table");
            table.find(".chk").each(function (i, it) {
                it.checked = _this.checked;
            });
        } else {
            var table = $(_this).parents("table");
            table.find(".chk").each(function (i, it) {
                it.checked = _this.checked;
            });
        }
    });

    //数据列表选中全部时,将全选按钮选中,反之将全选按钮置为未选中状态
    $(document).on("change", ".chk:checkbox", function () {
        var table = $(this).parents("table");
        var allChkSize = table.find(":input:checkbox").size() - 1;
        var checkedChkSize = table.find(".chk:checkbox:checked").size();
        var chkAll = table.find(".chkAll");
        var fixedtablehead = $(this).parents(".table-scrollable").attr("fixedtablehead");
        if (fixedtablehead) {
            chkAll = $("." + fixedtablehead).find(".fixedHead .chkAll")
        }
        if (chkAll.size() > 0) {
            if (allChkSize == checkedChkSize) {
                chkAll.get(0).checked = true;
            } else {
                chkAll.get(0).checked = false;
            }
        }
    });

    //数据表格右上角设置图标按钮
    $(document).on("click", '.searchCriteria .widget-buttons *[data-toggle="config"]', function (event) {
        event.preventDefault();
        var btn = $(this),
            widget = btn
        var ths = $(".dataTable thead th");//:not(.fixedColumn)");
        var width = 800;
        var height = 400;
        var bgDiv = '<div class="bgDiv" style="position:fixed; top:0px; background-color:rgba(226, 225, 225, 0.72); z-index:9997; opacity:0.5; left:0px; width:100%;height:' + $(window).height() + '"></div>';
        var div =
            '<div class="row configPanel" style="z-index:9998;background-color:#ffffff;width:' + width + 'px; min-height:' + height + 'px;max-height:' + height + 'px;position:absolute; left:' + ($(window).width() - width + 50) / 2 + '; top:' + ($(window).height() - height) / 2 + '">'
            + '<div class="well with-header configPanelHeader" style="padding:0px 0 0 0;height:38px;margin:0px;cursor: move;">'
            + '<div class="header theme">数据表格显示设置<div class="" style="float: right;"><a href="javascript:" onclick="closeSettingPan()"><i class="fa fa-times"></i></a></div></div>'
            + '</div>'
            + '<div style="float:left; border-bottom: 3px solid #fff;width:100%;min-height:' + (height - 41 + 2) + 'px;max-height:' + (height - 41 + 2) + 'px; color:#262626; box-shadow: 0 0 3px rgba(0,0,0,.2);margin:0px;padding:0px;background-color:#FFF; overflow-y:auto; ">'
            + '<table class="table table-bordered" style="font-size:12px; border: none; ">'
            + '<thead>'
            + '<tr>'
            + '<th style="width:150px; border-left:none;">列</th>'
            + '<th style="width:80px; text-align:center;">显示</th>'
            + '<th>固定于左侧</th>'
            + '<th style="border-right:none;">固定于右侧</th>'
            + '</tr>'
            + '</thead>'
            + '<tbody>';
        ths.each(function (i, th) {
            var html = $.trim($(th).text());
            if (html) {
                var isfixedColumn = $(th).hasClass("fixedColumn");
                var fixedAlign = $(th).attr("fixed-align");
                var fixedLeft = isfixedColumn && fixedAlign == "left" ? "yes" : "no";
                var fixedRight = isfixedColumn && (fixedAlign == "right" || !fixedAlign) ? "yes" : "no";
                var visible = $(th).is(":visible");
                var checked = visible ? "checked=true1" : "";
                var disabled = fixedRight == "yes" || fixedLeft == "yes" ? "disabled=true" : "";
                div += '<tr>'
                    + '<td style="width:150px; margin:0px; padding:2px 0 0 10px;border-left:none;">' + html + '</td>'
                    + '<td style="margin:0px; padding:2px; width:80px;">'
                    + '<div class="checkbox" style="margin:0px; padding:0px;">'
                    + '<label>'
                    + '<input type="checkbox" index="' + i + '" ' + disabled + ' ' + checked + ' class="columnShowOrHideChk">'
                    + '<span class="text"></span>'
                    + '</label>'
                    + '</div>'
                    + '</td>'
                    + '<td style="margin:0px; padding:2px;">'
                    + '<label style="margin:0px; padding:0px;">'
                    + '<input class="checkbox-slider slider-icon yesno fixedLeft" index="' + i + '" type="checkbox" needInit=' + fixedLeft + ' >'
                    + '<span class="text">&nbsp;&nbsp;</span>'
                    + '</label>'
                    + '</td>'
                    + '<td style="margin:0px; padding:2px;border-right:none;">'
                    + '<label style="margin:0px; padding:0px;">'
                    + '<input class="checkbox-slider slider-icon yesno fixedRight" index="' + i + '" type="checkbox" needInit=' + fixedRight + ' >'
                    + '<span class="text">&nbsp;&nbsp;</span>'
                    + '</label>'
                    + '</td>'
                    + '</tr>';
            }
        });
        div += '</tbody>'
            + '</table>'
            + '</div>'
            + '</div>'
            + '</div>';
        $("body").find(".bgDiv").remove().end().append(bgDiv);
        $("body").find(".configPanel").remove().end().append(div);
        $(".configPanel [needInit='yes']").click();
        $(".fixedLeft,.fixedRight").change(function () {
            var index = $(this).attr("index");
            var ths = $(".dataTable thead th");
            var th = ths.eq(index);
            var sumSize = ths.size();
            var chs = $(this).parents("tr").find(":checkbox");
            var showCtr = chs.eq(0);
            var leftCtr = chs.eq(1);
            var rightCtr = chs.eq(2);
            var leftFixed = leftCtr.get(0).checked;
            var rightFixed = rightCtr.get(0).checked;
            var isFixed = leftFixed || rightFixed;
            var align = $(this).hasClass("fixedLeft") ? "left" : "right";
            if (this.checked) {
                th.addClass("fixedColumn");
            } else {
                var thText = th.text();
                thText = th.hasClass("checkboxColumnTh") ? "checkbox" : thText;
                $(".fixedTable").remove();
                th.removeClass("fixedColumn").removeClass("hideTd").show();
                $(".dataTable tbody td:nth-child(" + sumSize + "n-" + (sumSize - index - 1) + ")").removeClass("hideTd").show();
            }
            th.attr("fixed-align", align);
            if (align == "left" && rightFixed) {
                rightCtr.get(0).checked = false;
            }
            if (align == "right" && leftFixed) {
                leftCtr.get(0).checked = false;

            }
            if (isFixed) {
                showCtr.get(0).checked = false;
                showCtr.attr("disabled", true);
            } else {
                showCtr.get(0).checked = true;
                showCtr.attr("disabled", false);
            }
            //处理冻结列
            fixedColumn();
        });
        $(".columnShowOrHideChk").on("change", function () {
            var index = $(this).attr("index");
            var ths = $(".dataTable thead th");
            var th = ths.eq(index);
            var sumSize = ths.size();
            if (!this.checked) {
                $(".dataTable tbody td:nth-child(" + sumSize + "n-" + (sumSize - index - 1) + ")").hide();
                th.hide();
            } else {
                $(".dataTable tbody td:nth-child(" + sumSize + "n-" + (sumSize - index - 1) + ")").show();
                th.show();
            }
        });
        elementMove($(".configPanelHeader"), $(".configPanel"), false);
    });

    //开关样式复框,点击时将值复制给目标输入框
    $(document).on("change", ".checkbox-slider,[type='checkbox'],[type='radio']", function (even) {
        var that = $(this);
        var targetinputname = that.attr("data-target-input-name")
        var form = that.attr("data-target-form-id")
        if (targetinputname) {
            var targetinput = $("[name=" + targetinputname + "]");
            if (form) {
                targetinput = $("#" + form + " [name=" + targetinputname + "]");
            }
            if (targetinput.size() > 0) {
                if (that.attr("type") == "radio") {
                    targetinput.val(that.val());
                } else {
                    targetinput.val(this.checked);
                }
            }
        }
    });
});

/**
 * jquery 元素移动
 * @param element 触发移动的jquery元素
 * @param moveElement 被动移动的jquery元素
 * @param isOverflow 是否只可以移除浏览器可见区域
 */
function elementMove(element, moveElement, isOverflow) {
    element.mousedown(function (e) {
        var offset = $(this).offset();
        var x = e.pageX - offset.left;
        var y = e.pageY - offset.top;
        $(document).bind("mousemove", function (ev) {
            var windowWidth = $(window).width();
            var windowHeight = $(window).height();
            var min_x = 16, min_y = 0;
            var max_x = windowWidth - moveElement.width() + 20, max_y = windowHeight - moveElement.height();
            var explorer = navigator.userAgent;
            if (explorer.indexOf("Firefox") >= 0) {
                max_y -= 0;
            } else if (explorer.indexOf("Chrome") >= 0) {
                max_y -= 45;
            } else {
                max_x -= 10;
                max_y -= 0;
            }
            var _x = ev.pageX - x;
            var _y = ev.pageY - y;
            if (isOverflow == false) {
                _x = _x < min_x ? min_x : _x;
                _x = _x > max_x ? max_x : _x;
                _y = _y < min_y ? min_y : _y;
                _y = _y > max_y ? max_y : _y;
            }
            moveElement.css({
                left: _x + "px",
                top: _y + "px"
            });
            return false;
        });
    });

    $(document).mouseup(function () {
        $(this).unbind("mousemove");
    })
}

/**
 * 关闭显示列选择层
 */
function closeSettingPan() {
    $("body").find(".bgDiv").remove();
    $("body").find(".configPanel").remove();
}

/**
 * 初始化图片放大预览
 * @param $selector jQuery对象
 */
function initImgPrev($selector) {
    if (!window.viewers) {
        window.viewers = {};
    }
    var viewerId = "viewer_" + Math.randomStr();
    var imgSize = $selector.find("img.imgViewer").css({"cursor": "pointer"}).attr("title", "点击查看原图").attr("imgPrev", true).size();
    if (imgSize != 0) {
        console.log("viewer(" + viewerId + ") initialization...");
        $selector.addClass(viewerId).attr("viewerId", viewerId).viewer();
    } else {
        (function (_$selector) {
            setTimeout(function () {
                var initCount = window.viewers[viewerId];
                initCount = initCount ? initCount : 0;
                if (initCount <= 3600) {//两个小时还未找到图片，停止递归
                    window.viewers[viewerId] = initCount + 1;
                    initImgPrev(_$selector);
                }
            }, 2000);
        })($selector);
    }
    window.viewers[viewerId] = $selector.find("img.imgViewer[imgPrev='true']").size();
    (function (_viewerId) {
        var timer = setInterval(function () {
            var _$selector = $("." + _viewerId);
            if (_$selector.size() == 0) {
                clearInterval(timer);
            }
            var size = _$selector.find("img.imgViewer[imgPrev!='true']").size();
            if (size != 0 || (_$selector.find("img.imgViewer[imgPrev='true']").size() - window.viewers[_viewerId] != 0)) {
                _$selector.find("img.imgViewer[imgPrev!='true']").css({"cursor": "pointer"}).attr("title", "点击查看原图").attr("imgPrev", true);
                if (window.viewers[_viewerId] != 0 || _$selector.attr("viewerId")) {
                    console.log("viewer(" + _viewerId + ") updating...");
                    _$selector.viewer("update");
                } else {
                    console.log("viewer(" + _viewerId + ") reinitialization...");
                    _$selector.viewer();
                }
                window.viewers[_viewerId] = _$selector.find("img.imgViewer[imgPrev='true']").size();
            }
        }, 1000);
    })(viewerId);
}

/**
 * 异步请求
 *
 * @param url
 *            请求的URL
 * @param successCallBack
 *            请求成功回调函数
 * @param errorCallBack
 *            请求失败回调函数
 * @param type
 *            请求方式
 * @param resposneDataType
 *            服务器端数据响应格式
 */
function ajaxRequest(url, params, successCallBack, errorCallBack, type, resposneDataType) {
    if (!type) {
        type = "POST";
    }
    if (!resposneDataType) {
        resposneDataType = "html";
    }
    if (!params) {
        params = {};
    }
    $.ajax({
        type: type,
        url: url,
        cache: false,
        data: params,
        dataType: resposneDataType,
        beforeSend: function (XMLHttpRequest) {
            $(".loading-ajax").removeClass("ajaxLoaded").addClass("ajaxLoading");
        },
        success: function (data) {
            if (data.resCode == 500) {
                setMainViewHtml("error-500", true, true);
                $(".modal").modal("hide");
            } else {
                if (typeof successCallBack === "function") {
                    successCallBack(data);
                } else {
                    ajaxError("未找到可执行的回到函数");
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var responseText = XMLHttpRequest.responseText;
            if (responseText) {
                if (responseText.indexOf("<title>Error 404</title>") > -1) {
                    setMainViewHtml("error-404", true, true);
                    $(".modal").modal("hide");
                    return;
                } else if (responseText.indexOf("<title>Error 500</title>") > -1) {
                    setMainViewHtml(responseText);
                    $(".modal").modal("hide");
                    return;
                } else if (responseText.indexOf("<title>Error 403</title>") > -1) {
                    setMainViewHtml("error-403", true, true);
                    $(".modal").modal("hide");
                    return;
                } else if (responseText.indexOf("<title>Error 405</title>") > -1) {
                    setMainViewHtml("error-405", true, true);
                    $(".modal").modal("hide");
                    return;
                } else if (responseText.indexOf("<html>") > -1) {
                    setMainViewHtml(responseText, false);
                    $(".modal").modal("hide");
                }
            }
            if (typeof errorCallBack === "function") {
                errorCallBack(XMLHttpRequest, textStatus, errorThrown);
            } else {
                $(".modal").modal("hide");
                console.log(XMLHttpRequest);
                console.log(textStatus);
                console.log(errorThrown);
                ajaxError("服务器端异常 " + errorThrown);
            }
        },
        complete: function (XMLHttpRequest) {
            // console.log(XMLHttpRequest);
            $(".loading-ajax").removeClass("ajaxLoading").addClass("ajaxLoaded");
        }
    });
}

/**
 * 登录系统
 *
 * @param formId
 *            登录表单id
 */
function login(formId) {

    var loginUserName=$("[name='userName']");
    var password=$("[name='password']");
    var error=$(".errorInfo");
    if(/^\s*$/.test(loginUserName.val())){
        error.html("请输入用户名!");
        loginUserName.focus();
        return false;
    }
    if(/^\s*$/.test(password.val())){
        error.html("请输入密码!");
        password.focus();
        return false;
    }
    var url = "login/login.do";
    var params = $("#" + formId).serializeArray();
    ajaxRequest(url, params, function (result) {
            if (result.resCode == "200") {
                //缓存菜单权限
                sessionStorage.setItem("menus", result.data);
                var topWin = getTopWin();
                if (topWin.loginTimeOutDialog) {
                    topWin.loginTimeOutDialog.modal('hide');
                    topWin.$("form").each(function (i, form) {
                        try {
                            resetValidatorForm(form, false);
                        } catch (e) {
                        }
                    });
                    topWin.loginTimeOutDialog = null;
                } else {
                    if (/^\s*$/.test(ctx)) {
                        topWin.location.href = "sys_index";
                    } else if (/^.*\/$/.test(ctx)) {
                        topWin.location.href = ctx + "sys_index";
                    } else {
                        topWin.location.href = ctx + "/sys_index";
                    }
                }
            } else {
                error.html(result.resMsg);
                //重置formKey、formToken
                $("#" + formId).find("[name='formKey']").val(Math.randomStr());
                $("#" + formId).find("[name='formToken']").val(Math.randomStr());
            }
        },
        function (XMLHttpRequest, textStatus, errorThrown) {
            ajaxError(errorThrown);
        },
        "POST", "JSON");
}

/**
 * 注销系统
 */
function logout() {
    var url = "login/logout.do";
    ajaxRequest(url, null, function (data) {
            if (data.resCode == "200") {
                getTopWin().location.href = "switchView.do?viewPath=sysPage/login";
            } else {
                ajaxError(data.resMsg);
            }
        },
        function (XMLHttpRequest, textStatus, errorThrown) {
            ajaxError(errorThrown);
        },
        "GET", "JSON");
}

/**
 * 菜单切换
 *
 * @param viewPath
 *            视图路径
 * @param isRecord
 *              是否记录视图路径
 * @param method
 *              请求方式
 * @param params
 *              参数
 */
function toView(viewPath, isRecord, method, params,containerId) {
    if(!viewPath){
        return;
    }
    if (viewPath.indexOf("?") > -1) {
        viewPath += "&timer=" + new Date().getTime();
    } else {
        viewPath += "?timer=" + new Date().getTime();
    }
    if (!method) {
        method = "POST";
    }
    if (!params) {
        params = {};
    }
    ajaxRequest(viewPath, params, function (mainHtml) {
            var sityVal = '';
            for(var i in params){
                if(params[i].name=="schoolCity"){
                    sityVal = params[i].value;
                }
            }
            if (isRecord == undefined) {
                isRecord = false;
            }
            if (isRecord) {
                saveHistoryView(viewPath, params, method);
            }
            if (mainHtml.indexOf("<title>登录</title>") > -1) {
                showLoginDialog();
            } else {
                if (containerId) {
                    $("#" + containerId).html(mainHtml);
                } else {
                    setMainViewHtml(mainHtml, false);
                    setTimeout(function () {
                        if(params[0]){
                            console.log(params)
                            $(".search_Bar_item").each(function (i,searchItem) {
                                if($(searchItem).find("select").size()>0){
                                    var name = $(searchItem).find("select").attr("name");
                                    for(var o in params){
                                        if(name == params[o].name){
                                            $(searchItem).find("select").val(params[o].value);
                                            if(params[o].value){
                                                ajaxRequest("sysCitysController/getChildrens.do", {
                                                    pId: params[o].value
                                                }, function (result) {
                                                    var data = result.data;
                                                    var arr = ['<option value="">请选择</option>'];
                                                    $.each(data, function (i, t) {
                                                        arr.push('<option value="' + t.id + '">' + t.name + '</option>');
                                                    })
                                                    $(".schoolCity").html(arr.join(''));
                                                    $("#schoolCity").val(sityVal)

                                                }, function () {
                                                    ajaxError("加载城市失败")
                                                }, "get", "json")
                                            }
                                        }
                                    }
                                }

                            })


                        }
                    },50)
                }
            }
        },
        function (XMLHttpRequest, textStatus, errorThrown) {
            ajaxError(errorThrown);
        },
        method, "HTML");
}

/**
 * 保存历史视图
 * @param viewPath 视图路径
 * @param params 视图参数
 * @param method 请求方法
 */
function saveHistoryView(viewPath, params, method) {
    if (!window.historyViews) {
        window.historyViews = new Array();
        window.historyViewMethods = new Array();
        window.viewIndex = 0;
    } else {
        window.viewIndex = window.historyViews.length;
    }
    var existsVmpi = null;
    for (var i = 0, len = window.historyViews.length; i < len; i++) {
        var vmpi = window.historyViews[i];
        if (vmpi.viewPath == viewPath) {
            existsVmpi = vmpi;
            break;
        }
    }
    if (existsVmpi) {
        var existsVmpiIndex = existsVmpi.index;
        for (var i = existsVmpiIndex, len = window.historyViews.length - 1; i < len; i++) {
            window.historyViews[i] = window.historyViews[i + 1];//后边前移
        }
    }
    var view = {
        viewPath: viewPath,
        method: method,
        params: params,
        index: window.historyViews.length
    };
    window.historyViews.push(view);
    window.nowView = view;
}

/**
 * 显示超时登陆框
 */
function showLoginDialog() {
    getTopWin().loginTimeOutDialog = getTopWin().bootbox.dialog({
        title: '<i class="fa fa-lock red"></i>&nbsp;&nbsp;Login timeout, please login again',
        message: '<iframe src="switchView.do?viewPath=sysPage/login_old" style="width:600px;height: 400px;margin: -15px;border:none;"></iframe>',
        className: 'animated rotateIn',
        closeButton: false
    });
}

/**
 * 分页跳转
 * @param formId 分页表单Id
 * @param pageNo 要逃转的页码
 * @param pageSize 显示记录数
 * @param containerId 存放返回结果的容器id
 * @returns {boolean}
 */
function goPage(formId, pageNo, pageSize, containerId) {
    if (!formId || $("#" + formId).size() == 0) {
        ajaxError("参数错误,无法进行翻页(未指定分页表单)!");
        return false;
    }
    if (pageNo == null || pageNo == undefined) {
        pageNo = 1;
    }
    if (pageSize == null || pageSize == undefined) {
        pageSize = 15;
    }
    var pageForm = $("#" + formId);
    var url = pageForm.attr("action");
    if (pageForm.find("[name='pageNo']").size() == 0) {
        pageForm.append("<input type='hidden' name='pageNo' value='" + pageNo + "'/>");
    } else {
        pageForm.find("[name='pageNo']").val(pageNo);
    }
    if (pageForm.find("[name='pageSize']").size() == 0) {
        pageForm.append("<input type='hidden' name='pageSize' value='" + pageSize + "'/>");
    } else {
        pageForm.find("[name='pageSize']").val(pageSize);
    }
    var method = pageForm.attr("method");
    var params = pageForm.serializeArray();
    toView(url, true, method, params, containerId);

    var showVal = $("#iconchangemore").attr("value");
    setTimeout(function () {
        $("#iconchangemore").attr("value",showVal);
        if(showVal=="0"){
            $("#iconchangemore .fa").removeClass("fa-chevron-down").addClass("fa-chevron-up");
            $(".search_Bar_item").each(function () {
                $(this).removeClass("hidden");
            })
        }
    },200)
}

/**
 * 分页栏跳转按钮点击跳转
 * @param jumpBtn 调转按钮DOM对象
 * @param formId 分页表单Id
 * @param oldPageSize 当前页显示记录数
 * @param currentPageNo 当前页
 * @param totalPage 总码数
 * @param sumCount 总记录数
 */
function jump(jumpBtn, formId, oldPageSize, currentPageNo, totalPage, sumCount, containerId) {
    var targetPageNo = $(jumpBtn).parents(".pagingininfo").find("[name='targetPageNo']");
    var targetPageSize = $(jumpBtn).parents(".pagingininfo").find("[name='targetPageSize']");
    var pageNo = targetPageNo.val();
    var pageSize = targetPageSize.val();
    if (isNaN(pageNo) || pageNo > totalPage || pageNo < 1) {
        targetPageNo.val(currentPageNo);
        return;
    }
    if (isNaN(pageSize)) {
        targetPageSize.val(oldPageSize);
        return;
    }
    if (pageNo == currentPageNo && oldPageSize == pageSize) {
        return;
    }
    if (pageNo != 1) {
        if (pageNo * pageSize > sumCount) {
            var tempTotalPage = Math.ceil(sumCount / pageSize);
            pageNo = tempTotalPage > pageNo ? pageNo : tempTotalPage;
            targetPageNo.val(pageNo);
        }
    }
    goPage(formId, pageNo, pageSize, containerId);

    var showVal = $("#iconchangemore").attr("value");
    setTimeout(function () {
        $("#iconchangemore").attr("value",showVal);
        if(showVal=="0"){
            $("#iconchangemore .fa").removeClass("fa-chevron-down").addClass("fa-chevron-up");
            $(".search_Bar_item").each(function () {
                $(this).removeClass("hidden");
            })
        }
    },200)
}

/**
 *刷新主视图区
 */
function refunshView() {
    var nowView = window.nowView;
    if (!nowView) {
        return;
    }
    if (window.historyViews) {
        toView(nowView.viewPath, false, nowView.method);
    }
}

/**
 * 后退
 */
function backView() {
    var nowView = window.nowView;
    if (!nowView) {
        return;
    }
    if (window.historyViews) {
        if (nowView.index - 1 < 0) {
            window.location.reload();
        } else {
            var prevView = window.historyViews[nowView.index - 1];
            toView(prevView.viewPath, true, prevView.method, prevView.params);
        }
    }
}

/**
 * 设置主视区内容
 * @param content 主视区内容或主视区需要加载的内容URL
 * @param isLoad content是否为URL
 * @param isUseIframe 是否采用嵌入iframe形式加载URL
 */
function setMainViewHtml(content, isLoad,isUseIframe) {
    var mainView = $("body > div.main-container.container-fluid > div > div.page-content > div.page-body");
    $(".page-body").css("padding-right", "15px");
    if (!isLoad) {
        mainView.html(content);
    } else {
        if (!isUseIframe) {
            mainView.load(content);
        } else {
            $(".page-body").css("padding-right", "0px");
            if (content) {
                if (content.indexOf("?") != -1) {
                    content += "&" + new Date().getTime();
                } else {
                    content += "?" + new Date().getTime();
                }
            }
            mainView.html("<iframe src=" + content + " style='width:100%;height:100%;border:none;margin-top:-15px;'></iframe>");
        }
    }

    //筛选区自动布局
    autoLayoutSearchBar();

    //监听布局，调整冻结列表宽度
    $(".dataTable").parents(".widget").resize(function () {
        if (detectZoom() == 100) {
            widgetAutoLayout(this);
        }
    });

    setTimeout(function () {
        var startTime = new Date().getTime();
        //处理冻结列
        fixedColumn();
        var endTime = new Date().getTime();
        console.log("sumTime:" + (endTime - startTime));
    }, 100);
    /*
    // 自定义滚动条
    var explorer = navigator.userAgent;
    if(explorer.indexOf("Chrome") < 0){
        $(".page-body:first").unbind("mCustomScrollbar").mCustomScrollbar({
            set_width:"100%",
            set_height:(window.viewHeight+20)+"px",
            autoHideScrollbar:true,
            theme:"dark-thin",
            scrollInertia:0,
            autoDraggerLength:true,
            autoHideScrollbar:false,
            advanced:{
                updateOnBrowserResize:true,
                updateOnContentResize:true,
                autoExpandHorizontalScroll:false,
                autoScrollOnFocus:false,
                normalizeMouseWheelDelta:false
            },
        });
    }*/

    //修改面包屑导航
    var nowMenu = $($(".activeMenu:not('.open'):last").html()).find("i").remove().end().html();
    $("#nowActiveMenuName").html(nowMenu);
}

//监听浏览器是否缩放
$(window).resize(function () {
    $(".page-sidebar .sidebar-menus").height($(this).height() - 155);
    if (detectZoom() != 100) {//缩放模式关闭固定列
        var dataTables = $(".dataTable");
        dataTables.each(function (index, it) {
            var dataTable = $(it);
            var widget = dataTable.parents(".widget");
            var dataTableScrool = dataTable.parents(".table-scrollable");
            dataTableScrool.css("width", "100%");
            widget.find(".fixedTable").hide();
            dataTable.find(".hideTd").show();
        });
    } else {//非缩放模式开启固定列
        var dataTables = $(".dataTable");
        dataTables.each(function (index, it) {
            var dataTable = $(it);
            var widget = dataTable.parents(".widget:first");
            var dataTableScrool = dataTable.parents(".table-scrollable");
            widget.find(".fixedTable").show();
            dataTable.find(".hideTd").hide();
            widgetAutoLayout(widget.get(0));
        });
    }
});

/**
 * 获取指定复选框选中的值字符串
 * @param inputName 复选框name属性值,默认是id
 * @param separator 分隔符,默认为逗号
 * @returns {String} 复选框选中的值字符串
 */
function getCheckedInputValues(inputName, separator) {
    if (!inputName) {
        inputName = "id";
    }
    if (!separator) {
        separator = ",";
    }
    var inputs = $("[name='" + inputName + "']:checked");
    var count = inputs.size();
    var values = "";
    for (var i = 0; i < count; i++) {
        values += inputs.eq(i).val();
        if (i != count - 1) {
            values += ",";
        }
    }
    return values;
}

/**
 * 检测浏览器是否放大缩小
 * @returns {Number} 缩放百分比,小于100则是缩小,反之放大
 */
function detectZoom() {
    var ratio = 0,
        screen = window.screen,
        ua = navigator.userAgent.toLowerCase();
    if (~ua.indexOf('firefox')) {
        if (window.devicePixelRatio !== undefined) {
            ratio = window.devicePixelRatio;
        }
    } else if (~ua.indexOf('msie')) {
        if (screen.deviceXDPI && screen.logicalXDPI) {
            ratio = screen.deviceXDPI / screen.logicalXDPI;
        }
    } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
        ratio = window.outerWidth / window.innerWidth;
    }
    if (ratio) {
        ratio = Math.round(ratio * 100);
    }
    // 360安全浏览器下浏览器最大化时诡异的outerWidth和innerWidth不相等
    if (ratio === 99 || ratio === 101) {
        ratio = 100;
    }
    return ratio;
}

/**
 * 筛选区自动布局
 */
function autoLayoutSearchBar() {
    var search_Bars = $(".search_Bar");
    search_Bars.each(function (i, it) {
        var search_Bar = $(it);
        var widget = search_Bar.parents(".widget");
        var widgetWidth = widget.width();
        var size = $(".search_Bar td").size() * 2;
        var sumWidth = size * 190;
        $(".search_Bar th").each(function (i, item) {
            sumWidth += $(item).find("label").width();
        });
        var avgWidth = sumWidth / (size * 2);
        var columnCount = Math.floor(widgetWidth / (avgWidth + 158));
        var ths = search_Bar.find(".searchAreaTable th");
        var searchAreaTable = search_Bar.find(".searchAreaTable");
        var th_td = searchAreaTable.find("td,th");
        var thCount = th_td.size();
        var nowIndex = 0;
        thCount = thCount % (columnCount * 2) == 0 ? thCount : (thCount + thCount % (columnCount * 2));
        for (var i = 0; i < thCount; i++) {
            if ((i + 1) % (columnCount * 2) == 0) {
                th_td.slice(nowIndex, i + 1 > thCount ? (thCount - 1) : (i + 1)).wrapAll("<tr></tr>");
                nowIndex = i + 1;
            }
        }
        searchAreaTable.children().children().children().insertBefore(searchAreaTable.children());
    });
}

/**
 * widget 自动计算数据表格宽度
 * @param _this widget DOM对象
 */
function widgetAutoLayout(_this) {
    $(_this).find(".table-scrollable").each(function (index, _scrollable) {
        var scrollable = $(_scrollable);
        var sumFixedColumnWidth = 0;
        var fixedColumn = scrollable;
        var count = 0;
        while (fixedColumn.prev().hasClass("fixedTable")) {
            fixedColumn = fixedColumn.prev();
            sumFixedColumnWidth += fixedColumn.width();
            count++;
        }
        var explorer = navigator.userAgent;
        if (explorer.indexOf("Firefox") >= 0) {
            //firefox
            scrollable.width($(_this).width() - parseInt(sumFixedColumnWidth) - 3.1);
        } else if (explorer.indexOf("Chrome") >= 0) {
            //Chrome
            scrollable.width($(_this).width() - parseInt(sumFixedColumnWidth) - count - 0.5);
        } else {
            scrollable.width($(_this).width() - parseInt(sumFixedColumnWidth) - 3.1);
        }
    });
}

/**
 * 从表格中提取需要冻结的列进行冻结处理
 */
function fixedColumn() {
    var loadImg = $(".pagingBar .pagingininfo .loadingImg");
    loadImg.show();
    $(".fixedTable").remove();
    if ($(".fixedColumn").size() > 0) {
        $(".page-body").css("overflow", "hidden");
    } else {
        $(".page-body").css("overflow", "auto");
    }
    var isNotDate = false;
    $(".widget").each(function (widget_index, _widget) {
        var widget = $(_widget);
        widget.find(".table-scrollable:first .fixedColumn").each(function (index, _column) {
            var colum = $(_column);
            var tableScrollable = colum.parents(".table-scrollable");
            tableScrollable.width("auto");
            if (isNotDate) {
                return;
            }
            var thsStr = "";
            var tbodyStr = "";
            var thText = colum.text();
            thText = colum.hasClass("checkboxColumnTh") ? "checkbox" : thText;
            colum.prev().css("border-right", "none");
            var thSiblingsCount = colum.siblings().size();
            var fixedColumnIndex = colum.index();
            var table = colum.parents("table");
            var tbodys = table.find("tbody");
            var fixedTableWidth = colum.outerWidth();
            var cssWidth = _column.style.width;
            fixedTableWidth = cssWidth ? parseInt(cssWidth.split("px")[0]) : fixedTableWidth;
            if (index < $(".fixedColumn").size() - 1) {
                thsStr += "<th class='" + colum.attr("class") + "' style='";
            } else {
                thsStr += "<th class='" + colum.attr("class") + "' style='";
            }
            if (colum.hasClass("checkboxColumnTh")) {
                thsStr += "padding:7px 8px 7px 8px ;white-space: nowrap;";
            }
            thsStr += "'>" + colum.html() + "</th>";
            var oldClass = colum.attr("class");
            oldClass = oldClass.replace("hideTd", "") + " hideTd";
            colum.attr("class", oldClass);
            tbodys.each(function (index1, _tbody) {
                tbodyStr += "<tbody>";
                var tbody = $(_tbody);
                if (isNotDate) {
                    return;
                }
                isNotDate = !isNotDate && tbody.children().size() == 1;
                if (isNotDate) {
                    var td = tbody.find("tr:first td");
                    if ($.trim(td.text()) == "无数据") {
                        td.attr("colspan", thSiblingsCount);
                        return;
                    } else {
                        isNotDate = false;
                    }
                }
                tbody.find("tr td:nth-child(" + (thSiblingsCount + 1) + "n+" + (fixedColumnIndex + 1) + ")").each(function (index2, _td) {
                    var td = $(_td);
                    fixedTableWidth = Math.max(fixedTableWidth, td.outerWidth());
                    var tdHtml = td.html();
                    td.prev().css("border-right", "none");
                    tbodyStr += "<tr><td style='vertical-align: middle;white-space: nowrap;";
                    var tdWidth = "0px";
                    if (colum.hasClass("checkboxColumnTh")) {
                        fixedTableWidth = 23;
                        tdWidth = "width:" + fixedTableWidth + "px!important;";
                    }
                    tbodyStr += "" + tdWidth + "' align=\"center\">" + tdHtml + "</td></tr>";
                    var oldclass = td.attr("class");
                    oldclass = oldclass ? (oldclass.replace("hideTd", "") + " hideTd") : " hideTd";
                    td.attr("class", oldclass)
                    td.hide();
                });
                tbodyStr += "</tbody>";
            });
            if (tableScrollable.size() > 0) {
                colum.hide();
                var fixedAlign = colum.attr("fixed-align");
                if (!fixedAlign || fixedAlign != "left") {
                    fixedAlign = "right";
                }
                var fixedTable = "<table targetcolumn='" + thText + "' class=\"fixedTable " + fixedAlign + "FixedTable table table-bordered\" ";
                fixedTable += "style='display:none;'";
                fixedTable += ">";
                fixedTable += "<thead>";
                fixedTable += "<tr>";
                fixedTable += thsStr;
                fixedTable += "</tr>";
                fixedTable += "</thead>";
                fixedTable += tbodyStr;
                fixedTable += "</table>";
                tableScrollable.outerWidth(tableScrollable.width() - fixedTableWidth);

                var border_right = "1px";
                if (colum.hasClass("checkboxColumnTh")) {
                    border_right = "none";
                }
                if (index == 0) {
                    $(fixedTable).hide().insertBefore(tableScrollable).css({
                        float: fixedAlign,
                        position: "relative",
                        top: "0px",
                        right: "0px",
                        width: fixedTableWidth + "px",
                        "border-right": border_right
                    });
                } else {
                    if (fixedAlign == "right") {
                        $(fixedTable).hide().insertBefore(tableScrollable.parent().find(".table").first()).css({
                            float: fixedAlign,
                            position: "relative",
                            top: "0px",
                            right: "0px",
                            width: fixedTableWidth + "px",
                            "border-right": border_right
                        });
                    } else {
                        $(fixedTable).hide().insertBefore(tableScrollable.parent().find(".table").first()).css({
                            float: fixedAlign,
                            position: "relative",
                            top: "0px",
                            right: "0px",
                            width: fixedTableWidth + "px",
                            "border-right": border_right
                        });
                    }
                }
            }
            if (colum.hasClass("checkboxColumnTh")) {
                $(fixedTable).css("border-right", "none");
                border_right = ":none";
            }
            widgetAutoLayout(_widget);
            tableScrollable.css({
                "border-left": "none",
                "border-right": "none"
            }).show(function () {
                $(".page-body").css("overflow", "auto");
                widgetAutoLayout(_widget);
            });
        });

        widget.find(".rightFixedTable").each(function (index, _table) {
            var table = $(_table);
            table.show();
            if (index > 0) {
                table.css("border-right", "none").find("th,td").css("border-right", "none");
            }
            setFixedTableTdHeight(table);
        });
        widget.find(".leftFixedTable").each(function (index, table) {
            var table = $(table);
            table.show();
            var size = $(".leftFixedTable").size();
            if (size > 1 && index != size - 2) {
                table.css("border-right", "none").find("th,td").css("border-right", "none");
            }

            var tableScroll = widget.find(".dataTable");
            var ths = tableScroll.find("th");
            size = ths.size();
            for (var i = 0; i < size; i++) {
                if (!ths.eq(i).hasClass("fixedColumn")) {
                    ths.eq(i).css("border-left", "none");
                    tableScroll.find("tr td:nth-child(" + ths.size() + "n+" + (i + 1) + ")").css({
                        "border-left": "none"
                    });
                    break;
                }
            }
            setFixedTableTdHeight(table);
        });
        if (widget.find(".leftFixedTable").size() > 0) {
            widget.find(".checkboxColumnTh").parents(".leftFixedTable").insertBefore($(".leftFixedTable:first"));
        }
    });
    loadImg.hide();
}

/**
 * 设置固定列表格高度
 * @param table 表格jQuery对象
 */
function setFixedTableTdHeight(table) {
    var dataTable = table.parents(".widget").find(".dataTable");
    table.find("tr").each(function (ii, _tr) {
        var tr = $(_tr);
        var height = 0;
        dataTable.find("tr").eq(ii).find("td").each(function (hh, _td) {
            var td = $(_td);
            height = Math.max(td.height(), height);
        });
        tr.find("td").each(function (jj, _td) {
            var td = $(_td);
            height = Math.max(td.height(), height);
        });
        dataTable.find("tr").eq(ii).find("td").each(function (hh, _td) {
            var td = $(_td);
            td.height(height);
        });
        tr.find("td").each(function (jj, _td) {
            var td = $(_td);
            td.height(height);
        });
    });
}

/** 获取最顶层父windows对象
 * @returns
 */
function getTopWin() {
    var topWin = (function (p, c) {
        while (p != c) {
            c = p;
            p = p.parent;
        }
        return c;
    })(window.parent, window);
    return topWin;
}

/**
 * 回到默认欢迎页
 */
function goHome() {
    getTopWin().location.href = "sys_index";
}

/**
 * 将json转换成请求参数字符串
 * @param json
 * @returns {string}
 */
function jsonToRequestParams(json) {
    var paramsStr = "";
    $.each(json, function (key, value) {
        if (typeof(value) === "object") {
            value = encodeURI(JSON.stringify(value));
        }
        paramsStr += key + "=" + value + "&";
    });
    return paramsStr + "timer=" + new Date().getTime();
}

/**
 * 格式化Json字符串
 * @param json 需要格式化的字符串
 * @param options 参数
 * @returns {String} 格式化后的json字符串
 */
function formatJson(json, options) {
    var reg = null,
        formatted = '',
        pad = 0,
        PADDING = '    ';
    options = options || {};
    options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
    options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
    if (typeof json !== 'string') {
        json = JSON.stringify(json);
    } else {
        json = JSON.parse(json);
        json = JSON.stringify(json);
    }
    reg = /([\{\}])/g;
    json = json.replace(reg, '\r\n$1\r\n');
    reg = /([\[\]])/g;
    json = json.replace(reg, '\r\n$1\r\n');
    reg = /(\,)/g;
    json = json.replace(reg, '$1\r\n');
    reg = /(\r\n\r\n)/g;
    json = json.replace(reg, '\r\n');
    reg = /\r\n\,/g;
    json = json.replace(reg, ',');
    if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
        reg = /\:\r\n\{/g;
        json = json.replace(reg, ':{');
        reg = /\:\r\n\[/g;
        json = json.replace(reg, ':[');
    }
    if (options.spaceAfterColon) {
        reg = /\:/g;
        json = json.replace(reg, ': ');
    }
    $.each(json.split('\r\n'), function (index, node) {
        var i = 0,
            indent = 0,
            padding = '';

        if (node.match(/\{$/) || node.match(/\[$/)) {
            indent = 1;
        } else if (node.match(/\}/) || node.match(/\]/)) {
            if (pad !== 0) {
                pad -= 1;
            }
        } else {
            indent = 0;
        }
        for (i = 0; i < pad; i++) {
            padding += PADDING;
        }
        formatted += padding + node + '\r\n';
        pad += indent;
    });
    return formatted;
}

/**
 * 关闭弹出层
 * @param editFormId 弹层内部任意dom园所jquery对象
 */
function closeModal(innerJqObject) {
    if(innerJqObject){
        innerJqObject.parents(".modal-content").find(".modal-header .close").click();
    }
}

/**
 * 初始化列表table排序功能
 * @param tableSelector 列表jquery对象
 * @param ordersInputSelector 检索表单区域存放排序字符串的隐藏域jquery对象
 * @param callback 点击之后的回调函数
 */
function initOrderTable(tableSelector, ordersInputSelector, callback) {
    if (!tableSelector || !ordersInputSelector) {
        return;
    }
    var icons = '<div class="orderIcons">\n' +
        '      <i class="fa fa-sort-asc asc"></i>\n' +
        '      <i class="fa fa-sort-desc desc"></i>\n' +
        '</div>';
    tableSelector.find(".order").prepend(icons).click(function () {
        var th = $(this);
        var desc = "desc";// 降序
        var asc = "asc";// 升序
        var columnAndOrderTypeSeparator = ":";
        var separator = ";";
        var columnName = th.attr("columnName");// 字段名
        var orderStatus = th.attr("orderStatus");// 排序状态
        if (orderStatus == asc) {
            orderStatus = desc;
        } else if (orderStatus == desc) {
            orderStatus = "";
        } else {
            orderStatus = asc;
        }
        // 状态切换
        th.find(".orderIcons .fa").removeClass("active");
        th.attr("orderStatus", orderStatus);
        var $orders = ordersInputSelector;
        var ordersVal = $orders.val();
        ordersVal = ordersVal.replace(columnName + columnAndOrderTypeSeparator + asc, "").replace(columnName + columnAndOrderTypeSeparator + desc, "")
        if (orderStatus) {
            th.find(".orderIcons ." + orderStatus).addClass("active");
            var newOrderVal = ordersVal + separator + columnName + columnAndOrderTypeSeparator + orderStatus;
            $orders.val(newOrderVal.replace(/;+/g, ";"));
            if (typeof  callback === "function") {
                callback();
            }
        } else {
            var oldVal = ordersVal.replace(/;+/g, separator);
            $orders.val(oldVal == separator ? "" : oldVal);
        }
    });
}

/**
 * 移除文件使用记录
 * @param that 当前删除的小按钮对象
 * @param formId 表单id
 * @param targetDeleteInputName 记录删除文件的input的name属性值
 * @param targetHideInputName 记录未删除之前的最初的文件id的input的name属性值
 * @param fileId 要删除的文件id
 * @param needRemoveParentSelector 页面中需要移除的dom元素选择器
 */
function removeFileUseLog(that, formId, targetDeleteInputName, targetHideInputName, fileId, needRemoveParentSelector) {
    var useFileIds = $("#" + formId + " [name='" + targetHideInputName + "']");
    var targetDeleteInput = $("#" + formId + " [name='" + targetDeleteInputName + "']");
    var ids = useFileIds.val().split(",");
    var newIds = "";
    for (var i = 0, len = ids.length; i < len; i++) {
        if (ids[i] == fileId) {
            targetDeleteInput.val(targetDeleteInput.val() + "," + fileId);
            continue;
        }
        newIds += ids[i];
        if (i != len - 1) {
            newIds += ",";
        }
    }
    useFileIds.val(newIds);
    if (needRemoveParentSelector) {
        $(that).parents(needRemoveParentSelector).remove();
    } else {
        $(that).parents("p").remove();
    }
}

/**
 * 初始化验证表单
 * @param forms 表单对象
 */
function inintValidatorForm(forms) {
    forms = forms ? forms : $("form");
    return forms.bootstrapValidator().on('success.form.bv', function (e) {
        e.preventDefault();
        var url = "login/checkLogin.do?tiemr=" + new Date().getTime();
        ajaxRequest(url, {}, function (data) {//检查是否登陆超时
            if (data.resCode != "200") {
                showLoginDialog();
            } else {
                var form = $(e.target);
                var action = form.attr("action");
                var method = form.attr("method");
                var isRecord = form.attr("isCanRefresh");
                var responseType = form.attr("responseType");
                if (!method) {
                    method = "GET";
                }
                if (!responseType) {
                    responseType = "html";
                }
                var params = form.serializeArray();
                console.log(params);
                ajaxRequest(action, params, function (data) {
                    console.log("cllback:" + form.ajaxSubmitCallback);
                    form.trigger("ajaxSubmitCallback", data);
                    if (isRecord == "true") {
                        saveHistoryView(action, params, method);
                    }
                }, function (XMLHttpRequest, textStatus, errorThrown) {
                    ajaxError(errorThrown);
                }, method, responseType);
            }
        }, function (XMLHttpRequest, textStatus, errorThrown) {
            ajaxError(errorThrown);
        }, "POST", "JSON");
        return false;
    });
}

/**
 * 重置验证表单
 * @param form 需要重置的表单的DOM对象
 * @param isResetAllValue 是否重置所有表单元素值,默认：true
 */
function resetValidatorForm(_form, isResetAllValue) {
    if (isResetAllValue == undefined || (isResetAllValue != true && isResetAllValue != false)) {
        isResetAllValue = true;//将值和验证信息一起清空
    }
    var form = $(_form);
    form.bootstrapValidator('resetForm', isResetAllValue);
    if (isResetAllValue) {
        _form.reset();//清空所有数据
    }
}

/**
 * 初始化websocket
 * @param serverNameAndPort
 */
function initWebSocket(serverNameAndPort) {
    window.websocketConnectioned = false;
    var websocket;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://" + serverNameAndPort + ctxName + "/ws/talk?uid=" + loginAdminUserId);
    } else if ('MozWebSocket' in window) {
        websocket = new MozWebSocket("ws://" + serverNameAndPort + ctxName + "/ws/talk/" + loginAdminUserId);
    } else {
        websocket = new SockJS("http://" + serverNameAndPort + ctxName + "/ws/talk/sockjs" + loginAdminUserId);
    }
    websocket.onopen = function (event) {
        window.websocketConnectioned = true;
        console.log("WebSocket:已连接");
        console.log(event);
    };
    websocket.onmessage = function (event) {
        var data = JSON.parse(event.data);
        console.log("WebSocket:收到一条消息", data);
        if (data.type == "toUser") {//发给指定客户端
            if (data.to == sessionId + "-" + loginAdminUserId) {
                if (data.from == "-1" && data.content == "SystemLoginTimeoutNotify") {//登陆超时通知
                    Notify(data.sendTime + " 您本次登陆已超时或正常登出，请重新登陆!", 'bottom-right', '5000', 'danger', 'fa-bolt', true);
                    showLoginDialog();
                }
            }
        } else if (data.type == "broadcast") {//广播
            Notify(data.sendTime + " " + data.title + " " + data.content, 'bottom-right', '5000', 'danger', 'fa-bolt', true);
        }
    };
    websocket.onerror = function (event) {
        console.log("WebSocket:发生错误 ");
        console.log(event);
    };
    websocket.onclose = function (event) {
        console.log("WebSocket:已关闭");
        console.log(event);
    }
}

/**
 * 加载角色列表
 * @param containerId 列表显示容器Id
 * @param searchFormId 列表搜索表单id
 */
function loadRoleList(containerId, searchFormId) {
    var method = "POST";
    var params = {};
    if (!searchFormId) {
        searchFormId = "roleListSearchForm" + new Date().getTime();
    } else {
        params = $("#" + searchFormId).serializeArray();
    }
    var viewPath = "permissionSetting/roleList.do?searchFormId=" + searchFormId + "&containerId=" + containerId;
    console.log(params);
    ajaxRequest(viewPath, params, function (html) {
            if(typeof callback ==="function"){
                callback();
            }
            $("#" + containerId).html(html);
            var loadImg = $(".pagingBar .pagingininfo .loadingImg");
            loadImg.hide();
        },
        function (XMLHttpRequest, textStatus, errorThrown) {
            ajaxError(errorThrown);
        },
        method, "HTML");
}

/**
 * 加载用户列表
 * @param containerId 列表显示容器Id
 * @param searchFormId 列表搜索表单id
 */
function loadUserList(containerId, searchFormId) {
    var method = "POST";
    var params = {};
    if (!searchFormId) {
        searchFormId = "userListSearchForm" + new Date().getTime();
    } else {
        params = $("#" + searchFormId).serializeArray();
    }
    var viewPath = "permissionSetting/userList.do?searchFormId=" + searchFormId + "&containerId=" + containerId;
    ajaxRequest(viewPath, params, function (html) {
            $("#" + containerId).html(html);
            var loadImg = $(".pagingBar .pagingininfo .loadingImg");
            loadImg.hide();
        },
        function (XMLHttpRequest, textStatus, errorThrown) {
            ajaxError(errorThrown);
        },
        method, "HTML");
}